﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shapes;
using HandyControl.Controls;
using SmartSQL.Framework.PhysicalDataModel;
using Path = System.IO.Path;

namespace SmartSQL.CodeGen
{
    public class GenCodes
    {
        public static string GetColumnType(string sqlDataType, string columnName)
        {
            if(columnName.ToUpper().StartsWith("IS"))
                return "System.Windows.Forms.DataGridViewCheckBoxColumn";

            // 统一转为小写避免大小写敏感问题
            switch (sqlDataType.ToLower())
            {
                case "bit":
                    return "System.Windows.Forms.DataGridViewCheckBoxColumn";

                case "tinyint": // 适用于状态枚举
                case "smallint":
                case "int":
                case "bigint":
                case "decimal":
                case "numeric":
                case "float":
                case "real":
                case "money":
                    return "System.Windows.Forms.DataGridViewTextBoxColumn";

                case "date":
                case "datetime":
                case "datetime2":
                case "smalldatetime":
                case "timestamp":
                    return "System.Windows.Forms.DataGridViewTextBoxColumn";

                case "char":
                case "varchar":
                case "text":
                case "nchar":
                case "nvarchar":
                case "ntext":
                    return "System.Windows.Forms.DataGridViewTextBoxColumn";

                case "uniqueidentifier":
                    return "System.Windows.Forms.DataGridViewTextBoxColumn";

                case "binary":
                case "varbinary":
                case "image":
                    return "System.Windows.Forms.DataGridViewImageColumn";

                // 特殊处理外键字段为下拉框
                case "fk_*": // 自定义约定：以 fk_ 开头的字段名视为外键
                    return "System.Windows.Forms.DataGridViewComboBoxColumn";

                default:
                    // 未知类型默认使用文本框
                    return "System.Windows.Forms.DataGridViewTextBoxColumn";
            }
        }

        static int pre = 0;
        public static void GenerateDataGridViewColumnCode(string tableName, string path, List<Column> columns)
        {
            var sb0 = new StringBuilder();
            var sb1 = new StringBuilder();
            var sb = new StringBuilder();

            pre++;
            pre++;

            int width = 90;
            sb1.AppendLine("this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {");

            foreach (var col in columns)
            {
                if (string.IsNullOrWhiteSpace(col.Comment)) continue;
                sb1.AppendLine($"    Col{pre + col.Name},");
                string columnType = GetColumnType(col.DataType, col.Name);
                sb0.AppendLine($"    private {columnType} Col{pre + col.Name};");
                sb.AppendLine($"// Col{pre + col.Comment}");
                sb.AppendLine($"    Col{pre + col.Name} = new {columnType}();");
                sb.AppendLine($"    Col{pre + col.Name}.Name = \"Col{pre + col.Name}\";");
                sb.AppendLine($"    Col{pre + col.Name}.HeaderText = \"{col.Comment}\";");
                sb.AppendLine($"    Col{pre + col.Name}.DataPropertyName = \"{col.Name}\";");
                sb.AppendLine($"    Col{pre + col.Name}.Width = {width};");

                if(col.Name.ToUpper().StartsWith("IS"))
                {
                    sb.AppendLine($"   Col{pre + col.Name}.IndeterminateValue = 0;");
                    sb.AppendLine($"   Col{pre + col.Name}.TrueValue = 1;");
                    sb.AppendLine($"   Col{pre + col.Name}.FalseValue = 0;");
                }

                if (col.Name == "Id" || col.Name == "HeadId")
                    sb.AppendLine($"   Col{pre + col.Name}.ReadOnly = true;");

                if (col.DataType == "datetime")
                    sb.AppendLine($"   Col{pre + col.Name}.DefaultCellStyle.Format = \"yyyy-MM-dd\";");
            }

            sb1.AppendLine($"    }});");

            // 保存代码到文件
            string filePath = Path.Combine(path, $"Form{tableName}.DataGridView.cs");
            File.WriteAllText(filePath,
                sb0.ToString() + Environment.NewLine
                +sb.ToString() + Environment.NewLine
                + sb1.ToString()
                );
            Process.Start(path);
        }

        public static void GenerateFormCode(string tableName, string path, List<Column> columns)
        {
            var formCode = new StringBuilder();
            formCode.AppendLine("using System; using GKQC.Language;");
            formCode.AppendLine("using System.Collections.Generic;");
            formCode.AppendLine("using System.Windows.Forms;");
            formCode.AppendLine("using GKQC.DbHelper.DbModels;");
            formCode.AppendLine("using GKQC.DbHelper.Dao;");
            formCode.AppendLine("using GKQC.Common;");
            formCode.AppendLine("using SqlSugar;");
            formCode.AppendLine("using GKQC.DbHelper.Services;");
            formCode.AppendLine("using System.ComponentModel;");
            formCode.AppendLine("using System.Reflection;");
            formCode.AppendLine("using GKQC.DbHelper.ViewModels;");
            formCode.AppendLine("using ComponentFactory.LcrMes.Toolkit.QControls;");
            formCode.AppendLine("using System.Windows.Forms.VisualStyles;");
            formCode.AppendLine("using System.Linq;");
            formCode.AppendLine("using System.Drawing;");

            formCode.AppendLine();
            formCode.AppendLine($"namespace GKQC.FormGen");
            formCode.AppendLine("{");
            formCode.AppendLine($"    public partial class Form{tableName}");
            formCode.AppendLine("    {");
            formCode.AppendLine("        private System.ComponentModel.IContainer components = null;");
            formCode.AppendLine("                protected override void Dispose(bool disposing)\r\n        {\r\n            if (disposing && (components != null))\r\n            {\r\n                components.Dispose();\r\n            }\r\n            base.Dispose(disposing);\r\n        }");

            formCode.AppendLine("        #region");
            int cc = 0;
            // 生成控件声明
            foreach (var column in columns)
            {
                if (string.IsNullOrWhiteSpace(column.Comment))
                    continue;
                if (!column.Name.ToUpper().StartsWith("IS"))
                    formCode.AppendLine($"        private QLabel lbl{column.Name};");
                formCode.AppendLine($"        private {GetControlType(column)} {GetControlName(column)};");
            }
            formCode.AppendLine("        #endregion");

            // 生成初始化代码
            formCode.AppendLine("        private void InitializeComponent()");
            formCode.AppendLine("        {");
            formCode.AppendLine($"        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form{tableName}));");

            formCode.AppendLine("        #region");
            int y = 10;
            int x = 5;
            int width = 150;
            int space = 50;
            cc = 0;
            foreach (var column in columns)
            {
                if (string.IsNullOrWhiteSpace(column.Comment))
                    continue;
                if (x > 1200)
                {
                    x = 5; y += 28;
                }
                var controlName = GetControlName(column);
                if (!column.Name.ToUpper().StartsWith("IS"))
                {
                    formCode.AppendLine($"            this.lbl{column.Name} = new QLabel();");
                    formCode.AppendLine($"            this.lbl{column.Name}.Text = \"{column.Comment}\";");
                    formCode.AppendLine($"            this.lbl{column.Name}.Location = new Point({x}, {y + 5});");
                    formCode.AppendLine($"            this.lbl{column.Name}.AutoSize = true;");
                    formCode.AppendLine($"            this.lbl{column.Name}.Name = \"lbl{column.Name}\";");
                    formCode.AppendLine($"            this.lbl{column.Name}.BackColor = System.Drawing.Color.Transparent;");
                    //this.lblGTYPE_ID.BackColor = System.Drawing.Color.Transparent;
                    formCode.AppendLine($"            Controls.Add(this.lbl{column.Name});");
                }
                x += (width + 10);

                formCode.AppendLine($"            this.{controlName} = new {GetControlType(column)}();");
                formCode.AppendLine($"            this.{controlName}.Location = new Point({x}, {y});");
                formCode.AppendLine($"            this.{controlName}.Size = new System.Drawing.Size({width}, 25);");
                formCode.AppendLine($"            this.{controlName}.Name = \"{controlName}\";");
                formCode.AppendLine($"            this.{controlName}.InterField = \"{column.Name}\";");
                if (column.Name.ToUpper().StartsWith("IS"))
                {
                    formCode.AppendLine($"            this.{controlName}.Text = \"{column.Comment}\";");
                    formCode.AppendLine($"            this.lbl{controlName}.BackColor = System.Drawing.Color.Transparent;");
                }
                formCode.AppendLine($"            Controls.Add(this.{controlName});");
                x += (width + space);
            }
            formCode.AppendLine("        #endregion");
            formCode.AppendLine("        this.ResumeLayout(false);");
            formCode.AppendLine("        this.PerformLayout();");



            formCode.AppendLine("        }");

            formCode.AppendLine("    }");
            formCode.AppendLine("}");

            // 保存代码到文件
            string filePath = Path.Combine(path, $"Form{tableName}.Designer.cs");
            File.WriteAllText(filePath, formCode.ToString());
            Process.Start(path);

            try
            {
                GenerateDataGridViewColumnCode(tableName, path, columns);
            }
            catch ( Exception ex)
            {
                System.Windows.MessageBox.Show("生成表格列代码异常：" + ex.Message);
            }
        }

        // 生成.cs文件内容
        public static void GenerateLogicCode(string tableName, string path)
        {
            var codes = $@"
                using System.Windows.Forms;
                using GKQC.Common;

                namespace GKQC.FormGen
                {{
                    public partial class Form{tableName} : QcFormBase
                    {{
                        public Form{tableName}()
                        {{
                            InitializeComponent();
                            this.Text = ""{tableName} 自动生成界面"";
                            this.Size = new System.Drawing.Size(1200, 600);
                            WindowState = FormWindowState.Maximized;
                        }}
                    }}
                }}";

            // 保存代码到文件
            string filePath = Path.Combine(path, $"Form{tableName}.cs");
            File.WriteAllText(filePath, codes);
            Process.Start(path);
        }

        public static string GetControlType(Column column)
        {
            if (column.Name.ToUpper().StartsWith("IS"))
                return "QCheckBox";
            switch (column.DataType.ToLower())
            {
                case "datetime":
                    return "QDateTimePicker";
                default:
                    return "QTextBox";
            }
        }

        public static string GetControlValue(Column column)
        {
            switch (GetControlType(column))
            {
                case "CheckBox":
                case "QCheckBox":
                case "LcrMesCheckBox":
                    return $"{GetControlName(column)}.Checked";
                case "DateTimePicker":
                case "QDateTimePicker":
                case "LcrMesDateTimePicker":
                    return $"{GetControlName(column)}.Value";
                case "NumericUpDown":
                case "QNumericUpDown":
                case "LcrNumericUpDown":
                    return $"{GetControlName(column)}.Value";
                default:
                    return $"{GetControlName(column)}.Text";
            }
        }

        public static string GetControlName(Column column)
        {
            switch (GetControlType(column))
            {
                case "CheckBox":
                case "QCheckBox":
                case "LcrMesCheckBox":
                    return $"chk{column.Name}";
                case "DateTimePicker":
                case "QDateTimePicker":
                case "LcrDateTimePicker":
                    return $"dte{column.Name}";
                case "NumericUpDown":
                case "QNumericUpDown":
                case "LcrMesNumericUpDown":
                    return $"num{column.Name}";
                default:
                    return $"txt{column.Name}";
            }
        }
    }
}
